package com.example.hzq;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Netty客户端，用于测试服务器
 */
public class NettyClient {
    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
    
    private final String host;
    private final int port;
    private final String clientId;
    private Channel channel;
    private EventLoopGroup group;
    
    public NettyClient(String host, int port, String clientId) {
        this.host = host;
        this.port = port;
        this.clientId = clientId;
    }
    
    public void connect() throws Exception {
        group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .option(ChannelOption.SO_KEEPALIVE, true)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) {
                     ch.pipeline().addLast(
                         new StringDecoder(),
                         new StringEncoder(),
                         new ClientHandler(clientId)
                     );
                 }
             });
            
            // 连接服务器
            ChannelFuture f = b.connect(host, port).sync();
            this.channel = f.channel();
            logger.info("Client {} connected to {}:{}", clientId, host, port);
        } catch (Exception e) {
            logger.error("Client {} connection error", clientId, e);
            throw e;
        }
    }
    
    public void sendMessage(String message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
        } else {
            logger.error("Client {} is not connected", clientId);
        }
    }
    
    public void disconnect() {
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
        logger.info("Client {} disconnected", clientId);
    }
    
    public boolean isConnected() {
        return channel != null && channel.isActive();
    }
    
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 8080;
        String clientId = "client-" + System.currentTimeMillis();
        
        NettyClient client = new NettyClient(host, port, clientId);
        try {
            client.connect();
            client.sendMessage("Hello from " + clientId);
            
            // 保持连接一段时间
            TimeUnit.SECONDS.sleep(30);
        } finally {
            client.disconnect();
        }
    }
}
